package net.xdclass.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.controller.request.SendCodeRequest;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {
    /**
     * 10分钟
     */
    private static final long CAPTCHA_CODE_EXPIRED = 1000 * 60 * 10;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 生成验证码
     * @param request
     * @param response
     */
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        //创建验证码
        String producerText = captchaProducer.createText();
        log.info("生成验证码：{}" + producerText);
        // 存到redis
        redisTemplate.opsForValue().set(this.getKey(request),producerText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        BufferedImage image = captchaProducer.createImage(producerText);
        //response流封装
//        ServletOutputStream outputStream = null;
        //try-with-resources 优化try-catch
        try (ServletOutputStream outputStream = response.getOutputStream()){
//            outputStream = response.getOutputStream();
            //使用captcha谷歌的
            ImageIO.write(image, "png", outputStream);
            outputStream.flush();
//            outputStream.close();
            //关流
        } catch (IOException e) {
            log.error("获取流出错：{}",e.getMessage());
        }

    }

    private String getKey(HttpServletRequest request) {
        //使用工具类获取发送请求的ip+header
        String ipAddr = CommonUtil.getIpAddr(request);
        String header = request.getHeader("User-Agent");
        String key = "service-account"+CommonUtil.MD5(ipAddr+header);
        log.info("验证码key{}"+key);
        return key;
    }


    @PostMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {
        String key = this.getKey(request);
        String catchCaptcha = redisTemplate.opsForValue().get(key);
        String captcha = sendCodeRequest.getCaptcha();
        if (StringUtils.isNotEmpty(captcha) && StringUtils.isNotEmpty(catchCaptcha) && captcha.equals(catchCaptcha)) {
            //成功
            redisTemplate.delete(key);
            JsonData jsonData =  notifyService.sendCode(SendCodeEnum.USER_REGIDTER,sendCodeRequest.getTo());
            return jsonData;
        }else {
            return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);
        }

    }

}
